package utils

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
)

var (
	logger *log.Logger
)

func Init() {
	//basePath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	logPath := filepath.Join(".", "log")
	_, err := os.Stat(logPath)
	if err != nil && os.IsNotExist(err) {
		if err = os.Mkdir(logPath, os.ModePerm); err != nil {
			log.Fatalf("初始化日志失败: %v", err)
		}

	}
	fpath := filepath.Join(logPath, "log.log")
	logfile, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.ModePerm)
	if err != nil {
		log.Fatalf("打开日志文件%s失败: %v", fpath, err)
	}

	logger = log.New(logfile, "", log.Ldate|log.Ltime|log.Lshortfile)
}

func Println(info ...interface{}) {
	logger.Println(info)
}

func Fatalf(format string, v ...interface{}) {
	str := fmt.Sprintf(format, v)
	logger.Println(str, v)
	os.Exit(1)
}

func Errorf(format string, v ...interface{}) {
	str := fmt.Sprintf(format, v)
	logger.Panicln(str)
}

func Printf(format string, v ...interface{}) {
	str := fmt.Sprintf(format, v)
	logger.Println(str)
}

func GetLogger() *log.Logger {
	return logger
}
